<template>
  <div class="box">
    <el-form :inline="true">
      <el-form-item>
        <el-input
          placeholder="请输入内容"
          class="input-with-select"
          style="width: 400px"
        >
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success">添加商品</el-button>
      </el-form-item>
    </el-form>

    <div class="div">
      <div
        class="div_item"
        v-for="(item, index) in list"
        :key="index"
        @click="$router.push('/deail?id=' + item.id)"
      >
        <img v-lazy="item.pic" alt="" />
        <p class="title">{{ item.name }}</p>
        <p class="price">￥{{ item.originalPrice }}</p>
        <el-button @click.stop="addCart">加入购物车</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { Lazyload } from "vant";

Vue.use(Lazyload);
export default {
  name: "",
  data() {
    return {
      list: {},
    };
  },
  mounted() {
    // 调用
    this.goodsList();
  },
  methods: {
    goodsList() {
      this.$axios
        .get("https://api.it120.cc/small4/shop/goods/list")
        .then((res) => {
          console.log(res);
          this.list = res.data;
        });
    },
    // 加入购物车
    addCart() {
      // 如果用户未登录的话
      if (this.$store.state.token == "") {
        this.$dialog
          .confirm({
            title: "消息提示",
            message: "您还没登录 请登录后再操作",
          })
          .then(() => {
            this.$router.push("/login");
          })
          .catch(() => {
            this.$toast("您已取消");
          });
        return false;
      }else{
        // 执行加入购物车的操作
        // 加入购物车的商品的数据
        let cart ={
          id:this.list.id,
          pic:this.list.pic,
          price:this.list.price,
          name:this.list.name,
          num:1,
        };
        // 调用 vuex 中加入购物车的代码
        this.$store.commit('addCart',cart);

        this.$message.success('加入成功')
        this.$router.push('/cart')
      }
    },
  },
  computed: {},
  watch: {},
};
</script>

<style lang='scss' scoped>
.box {
  margin-top: 20px;
  .div {
    width: 100%;
    display: flex;
    padding: 10px;
    flex-wrap: wrap;
    .div_item {
      width: 18%;
      border: 1px solid #ddd;
      padding: 3px;
      margin: 10px;
      box-sizing: border-box;
      img {
        width: 100%;
        height: 260px;
      }
      .price {
        font-size: 20px;
        color: orange;
      }
      .title {
        line-height: 40px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .el-button {
        width: 100%;
        background: red;
        color: #fff;
      }
    }
  }
}
</style>